#!/usr/bin/env python
# encoding: utf-8
'''
Adb.RsHelper -- resource set helper 

Adb.RsHelper is a interface of handling the the resource set

It defines RsHelper

@author:     Anson Chan

@copyright:  2016 Xerland Co. Ltd. All rights reserved.

@contact:    anson_chan@xerland.com
@deffield    updated: Updated
'''
from AdbHelper import AdbHelper
import win32com.client
from Utils.TimeStamp import getNowDate
import datetime
import time
from Utils.adoconstants import *
from Utils.SysConstants import LOGGER

class RsHelper():
    '''
    resource set helper
    '''

    def __init__(self, rsName):
        '''
        Constructor
        '''
        self.adb = AdbHelper()
        self.mLastUpdateTime = datetime.datetime.now()
        self.mLastUpdateId = -1
        self.rsName = rsName
        self.rs = None
        
    def selectAll(self, order=""):
        self.rs = win32com.client.Dispatch(r'ADODB.Recordset')
        self.rs.Cursorlocation = 3
        self.rs.Open('Select * FROM ['+self.rsName+'] '+order, self.adb.getConn())
#Todo: query handling
        
#        print self.rs.Fields.Item("PowerOnTime")
#        self.rs.Close()
        return self.rs
        
    def selectColsWhere(self, cols, cond, ops=""):
        if not cols or not cond:
            LOGGER.error("cols or tab arguments empty!")
            return None
        conn = self.adb.getConn()
        self.rs = win32com.client.Dispatch(r'ADODB.Recordset')
        self.rs.Cursorlocation = 3
        
        sqlStr = None
        for col in cols:
            if sqlStr:
                sqlStr += "," + col
            else:
                sqlStr = "Select " + col
        sqlStr += " FROM [%s] WHERE %s %s" %(self.rsName, cond, ops)  
#        print sqlStr
        self.rs.Open(sqlStr, conn)
        return self.rs
        
        
    def selectUpdate(self, timeColum):
        self.selectAll()
        self.rs.MoveLast()
        cid = self.rs.Fields.Item("RecordID")
        updateTime = self.rs.Fields.Item(timeColum)
        while cid>self.mLastRsId and updateTime>self.mLastUpdateTime and self.rs != rs.BOF:
            self.rs.MovePrevious()
            
    
    def close(self):
        if self.rs.State == adStateOpen:
            self.rs.Close()
        self.adb.close()
    
if __name__ == '__main__':
    rs = RsHelper("PcPower")                
    rs.selectAll()
    rs.close()
        
        